package com.hyl.springbootappinfo.controller;

import com.alibaba.fastjson.JSON;
import com.hyl.springbootappinfo.pojo.*;
import com.hyl.springbootappinfo.service.App_categoryService;
import com.hyl.springbootappinfo.service.App_versionService;
import com.hyl.springbootappinfo.service.Data_dictionaryService;
import com.hyl.springbootappinfo.service.Dev_userService;
import com.hyl.springbootappinfo.web.tools.Constants;
import org.apache.commons.io.FilenameUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/dev")
public class DevController {

    @Autowired
    private Dev_userService dev_userService;

    @Autowired
    private Data_dictionaryService data_dictionaryService;

    @Autowired
    private App_categoryService app_categoryService;

    @Autowired
    private App_versionService app_versionService;

    @RequestMapping("/app/list")
    public String devAppList(@RequestParam(value = "queryStatus",required = false) Integer status,
                             @RequestParam(value = "querySoftwareName",required = false) String softwareName,
                             @RequestParam(value = "queryFlatformId",required = false) Integer flatformId,
                             @RequestParam(value = "queryCategoryLevel3",required = false) Integer categoryLevel3,
                             @RequestParam(value = "queryCategoryLevel1",required = false) Integer categoryLevel1,
                             @RequestParam(value = "queryCategoryLevel2",required = false) Integer categoryLevel2,
                             @RequestParam(value = "currentPageNo",required = false)Integer currentPageNo,
                             HttpServletRequest request){
        Dev_user login= (Dev_user) request.getSession().getAttribute(Constants.USER_SESSION);

        if (status==null){
            status=null;
        }
        if (softwareName==null){
            softwareName="";
        }
        if (flatformId==null){
            flatformId=null;
        }
        if (categoryLevel1==null){
            categoryLevel1=null;
        }
        if (categoryLevel2==null){
            categoryLevel2=null;
        }
        if (categoryLevel3==null){
            categoryLevel3=null;
        }

        request.setAttribute("querySoftwareName",softwareName);
        request.setAttribute("queryStatus",status);
        request.setAttribute("queryFlatformId",flatformId);
        request.setAttribute("queryCategoryLevel1",categoryLevel1);
        request.setAttribute("queryCategoryLevel2",categoryLevel2);
        request.setAttribute("queryCategoryLevel3",categoryLevel3);

        //游戏信息
        Integer pagesize=6;
        if (currentPageNo==null){
            currentPageNo=1;
        }

        request.setAttribute("currentPageNo",currentPageNo);
        currentPageNo=(currentPageNo-1)*pagesize;



        List<App_info> app_infoList= dev_userService.applist(status,currentPageNo,pagesize,softwareName,flatformId,categoryLevel3,categoryLevel1,categoryLevel2);

        request.setAttribute("appInfoList",app_infoList);

        //查询记录数
        int totalCount=dev_userService.count(status,softwareName,flatformId,categoryLevel3,categoryLevel1,categoryLevel2);
        request.setAttribute("totalCount",totalCount);

        int totalPageCount=totalCount/pagesize;
        totalPageCount=totalCount%pagesize==0?totalPageCount:totalPageCount+1;
        request.setAttribute("totalPageCount",totalPageCount);
//        //App状态信息
        List<Data_dictionary> data_dictionaryList=data_dictionaryService.finbyTypeName("APP状态");
        request.setAttribute("statusList",data_dictionaryList);

        //App所属平台
        List<Data_dictionary> flatFormList=data_dictionaryService.finbyTypeName1("所属平台");
        request.setAttribute("flatFormList",flatFormList);

//        //一级分类
        List<App_category> categoryLevel1List=app_categoryService.finbyparenId(0);
        request.setAttribute("categoryLevel1List",categoryLevel1List);

        request.setAttribute("devuser",login);

        return "developer/appinfolist";
    }

    //查看二级分类
    @RequestMapping("/categorylevellist")
    @ResponseBody
    public Object categoryLeve2List(@RequestParam Integer pid,HttpServletRequest request){
        List<App_category> categoryLevel2List=app_categoryService.finbyparenId(pid);
        String result=JSON.toJSONString(categoryLevel2List);
        return result;
    }

    //查看三级分类
    @RequestMapping("/categoryLeve3List")
    @ResponseBody
    public Object categoryLeve3List(@RequestParam Integer pid,HttpServletRequest request){
        List<App_category> categoryLevel3List=app_categoryService.finbyparenId(pid);
        String result=JSON.toJSONString(categoryLevel3List);
        return result;
    }

    //添加APP信息
    @RequestMapping("/app/appinfoadd")
    public String appinfoAdd(){
        return "developer/appinfoadd";
    }

    //添加页面查看所属平台
    @RequestMapping("/datadictionarylist.json")
    @ResponseBody
    public Object getflatform(String tcode){
        List<Data_dictionary> data_dictionaryList=data_dictionaryService.finbyTypeName(tcode);
        return JSON.toJSONString(data_dictionaryList);
    }

    //添加页面查看一级分类
    @RequestMapping("/categorylevellist.json")
    @ResponseBody
    public Object getcategorylevellist(Integer pid){
        List<App_category> app_categoryList=app_categoryService.finbyparenId(pid);
        return JSON.toJSONString(app_categoryList);
    }

    //添加页面查看二级分类
    @RequestMapping("/categorylevel2list.json")
    @ResponseBody
    public Object getcategorylevel2list(Integer pid){
        List<App_category> app_categoryList=app_categoryService.finbyparenId(pid);
        return JSON.toJSONString(app_categoryList);
    }

    //添加页面查看三级分类
    @RequestMapping("/categorylevel3list.json")
    @ResponseBody
    public Object getcategorylevel3list(Integer pid){
        List<App_category> app_categoryList=app_categoryService.finbyparenId(pid);
        return JSON.toJSONString(app_categoryList);
    }

    //添加页面判断APKName是否唯一
    @RequestMapping("/apkexist.json")
    @ResponseBody
    public Object getapkexist(String APKName){
        String data="empty";
        if (APKName.equals(null) || APKName.equals("")){
            data="empty";

        }else if (dev_userService.findAPKName(APKName)>0){
            data="exist";

        }else {
            data="noexist";
        }
        return JSON.toJSONString(data);

    }
    @RequestMapping(value = "/appinfoaddsave",method = RequestMethod.POST)
    public String getAppinfoaddsave(App_info app_info, HttpServletRequest request, @RequestParam("a_logoPicPath")MultipartFile a_logoPicPath){

        String logoPicPath=null;
        String path=request.getSession().getServletContext().getRealPath("statics"+ File.separator+"uploadfiles");
        if (!a_logoPicPath.isEmpty()){
            String oldFileName=a_logoPicPath.getOriginalFilename();     //原文件名
            String prefix= FilenameUtils.getExtension(oldFileName);     //原文件名后缀
            int fileSize=1024*500;
            if (a_logoPicPath.getSize()>fileSize){
                return "redirect:/dev/app/appinfoadd";
            }
            if (prefix.equalsIgnoreCase("jpn") || prefix.equalsIgnoreCase("jpg")){
                String fileName=app_info.getAPKName()+".jpg";
                File targeFile=new File(path,fileName);
                if (!targeFile.exists()){
                    targeFile.mkdirs();
                }
                try {
                    a_logoPicPath.transferTo(targeFile);

                } catch (IOException e) {
                    e.printStackTrace();
                }
                logoPicPath=fileName;
            }
        }
        Dev_user loginUser= (Dev_user) request.getSession().getAttribute(Constants.USER_SESSION);
        app_info.setCreatedBy(loginUser.getId());
        app_info.setCreationDate(new Date());
        app_info.setLogoPicPath(logoPicPath);
        app_info.setLogoLocPath(path+File.separator+logoPicPath);
        if (dev_userService.appinfoadd(app_info)>0){
            return "redirect:/dev/app/list";
        }else{
            return "redirect:/dev/app/appinfoadd";
        }

    }

    //跳转修改页面
    @RequestMapping("/appinfomodify")
    public String getAppinfomodify(Integer id,HttpServletRequest request){
        App_info app_info=dev_userService.findById(id);

        //查看app版本信息
        List<App_version> app_versionList = app_versionService.versionlist(id);
        request.setAttribute("appVersionList",app_versionList);

        //App状态信息

        Data_dictionary data_dictionary=data_dictionaryService.findbyTypeNameAndVauleId("APP状态",app_info.getStatus());
        app_info.setStatusName(data_dictionary.getValueName());

        request.setAttribute("appInfo",app_info);
        //App所属平台
        List<Data_dictionary> flatFormList=data_dictionaryService.finbyTypeName1("所属平台");
        request.setAttribute("flatFormList",flatFormList);
        request.setAttribute("queryFlatformId",app_info.getFlatformId());

        //一级分类
        List<App_category> categoryLevel1List=app_categoryService.finbyparenId(0);
        request.setAttribute("categoryLevel1List",categoryLevel1List);
        request.setAttribute("queryCategoryLevel1",app_info.getCategoryLevel1());

        return "developer/appinfomodify";
    }

    /**
     * 删除LOGO图片
     * @param id
     * @return
     */
    @RequestMapping("/delappinfofile.json")
    @ResponseBody
    public Object getDelappinfofile(@RequestParam("id")Integer id,HttpServletRequest request){

        App_info app_info=dev_userService.findById(id);
        File file=new File(app_info.getLogoLocPath());
        if (dev_userService.appinfofilemodify(id)>0){
            file.delete();
            return JSON.toJSONString("success");
        }else{
            return JSON.toJSONString("failed");
        }
    }

    //修改APP信息
    @RequestMapping(value = "appinfomodifysave",method = RequestMethod.POST)
    public String getAppinfomodifysave(App_info app_info, @RequestParam(value = "attach",required = false) MultipartFile logoPicPath
            ,HttpServletRequest request){

        String logoPicPaths=null;
        String path=request.getSession().getServletContext().getRealPath("statics"+ File.separator+"uploadfiles");
        if (logoPicPath!=null){
            String oldFileNme=logoPicPath.getOriginalFilename();    //原文件名
            String prefix=FilenameUtils.getExtension(oldFileNme);

            int filesize=1024*500;
            if (logoPicPath.getSize()>filesize){
                request.setAttribute("fileUploadError","图片不能超过500K");
                return "redirect:/app/appinfomodify";
            }else{
                if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("jpn")){
                    String fileName=app_info.getAPKName()+".jpg";
                    File file=new File(path,fileName);
                    if (!file.exists()){
                        file.mkdirs();
                    }
                    try {
                        logoPicPath.transferTo(file);
                    } catch (IOException e) {
                        request.setAttribute("fileUploadError","上传图片失败");
//                        e.printStackTrace();
                        return "redirect:/app/appinfomodify";
                    }
                    logoPicPaths=fileName;
                }else {
                    request.setAttribute("fileUploadError","文件名后缀必须为jpg、jpn");
                    return "redirect:/app/appinfomodify";
                }
            }
        }
        Dev_user loginUser= (Dev_user) request.getSession().getAttribute(Constants.USER_SESSION);

        app_info.setModifyBy(loginUser.getId());
        app_info.setModifyDate(new Date());
        if (logoPicPath!=null){
            app_info.setLogoPicPath(logoPicPaths);
            app_info.setLogoLocPath(path+File.separator+logoPicPaths);
        }
        if (dev_userService.appmodify(app_info)>0){
            return "redirect:/dev/app/list";
        }else{
            return "redirect:/dev/app/appinfoadd";
        }
    }


    //跳转查看页面
    @RequestMapping("/appview/{id}")
    public String getAppview(@PathVariable Integer id,HttpServletRequest request){
        App_info app_info=dev_userService.appview(id);
        request.setAttribute("appInfo",app_info);
        List<App_version> app_versionList = app_versionService.versionlist(id);
        request.setAttribute("appVersionList",app_versionList);
        return "developer/appinfoview";
    }

    //跳转新增版本页面
    @RequestMapping("/appversionadd")
    public String getAppversionadd(Integer id,HttpServletRequest request){
        List<App_version> app_versionList = app_versionService.versionlist(id);
        request.setAttribute("id",id);

        request.setAttribute("appVersionList",app_versionList);
        return "developer/appversionadd";
    }

    //新增版本信息
    @RequestMapping(value = "/addversionsave",method = RequestMethod.POST)
    public String getAddversionsave(App_version app_version,@RequestParam("a_downloadLink")MultipartFile a_downloadLink
                                    ,@RequestParam("id")Integer id,HttpServletRequest request){
        String path=request.getSession().getServletContext().getRealPath("statics"+ File.separator+"uploadfiles");
        String contextPath= request.getContextPath()+"/statics"+ File.separator+"/uploadfiles/";
        String fileName=null;
        if (!a_downloadLink.isEmpty()){
            String oldFileName=a_downloadLink.getOriginalFilename();
            String prefix=FilenameUtils.getExtension(oldFileName);
            if (prefix.equalsIgnoreCase("apk")){
                App_info app_info=dev_userService.findById(id);
                fileName=app_info.getAPKName()+".apk";
                File file=new File(path,fileName);
                if (!file.exists()){
                    file.mkdirs();
                }
                try {
                    a_downloadLink.transferTo(file);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else{
                request.setAttribute("fileUploadError","文件格式必须是APK");
                return "redirect:/dev/appversionadd";
            }
        }
        Dev_user loginUser= (Dev_user) request.getSession().getAttribute(Constants.USER_SESSION);
        app_version.setAppId(id);
        app_version.setCreatedBy(loginUser.getId());
        app_version.setCreationDate(new Date());
        app_version.setApkFileName(fileName);
        app_version.setApkLocPath(path+File.separator+fileName);
        app_version.setDownloadLink(contextPath+fileName);

        if (app_versionService.versionadd(app_version)>0){
            App_version app_versionList=app_versionService.findByAppid(id);
            if (dev_userService.versionmodify(id,app_versionList.getId())>0){
                return "redirect:/dev/app/list";
            }
        }
        return "redirect:/dev/appversionadd";

    }

    //跳转版本信息修改页面
    @RequestMapping("/appversionmodify")
    public String getAppversionmodify(@RequestParam("aid") Integer aid,@RequestParam("vid") Integer vid, HttpServletRequest request){
        List<App_version> app_versionList = app_versionService.versionlist(aid);


        App_version app_version=app_versionService.findByAppidAndVersionId(vid,aid);
        request.setAttribute("appVersionList",app_versionList);
        request.setAttribute("appVersion",app_version);
        return "developer/appversionmodify";
    }

    //删除游戏版本修改页面的apk文件
    @RequestMapping("/delfile.json")
    @ResponseBody
    public Object getDelfile(@RequestParam("id")Integer id,HttpServletRequest request){
        App_version app_version=app_versionService.findByAppid(id);
        File file=new File(app_version.getApkLocPath());

        if (app_versionService.deleapkName(id)>0){
            file.delete();
            return JSON.toJSONString("success");
        }else{
            return JSON.toJSONString("failed");
        }
    }

    //修改游戏版本信息
    @RequestMapping("/appversionmodifysave")
    public String getAppversionmodifysave(App_version app_version,@RequestParam(value = "attach",required = false) MultipartFile attach,HttpServletRequest request){

        String fileName=null;
        String path=request.getSession().getServletContext().getRealPath("statics"+ File.separator+"uploadfiles");
        String contextPath= request.getContextPath()+"/statics"+ File.separator+"/uploadfiles/";

        if (attach!=null){
            String oldName=attach.getOriginalFilename();
            String prefix=FilenameUtils.getExtension(oldName);  //拿文件名后缀
            if (prefix.equalsIgnoreCase("apk")){
                App_info app_infoList= dev_userService.findById(app_version.getAppId());
                fileName=app_infoList.getAPKName()+".apk";
                File file=new File(path,fileName);
                if (!file.exists()){
                    file.mkdirs();
                }
                try {
                    attach.transferTo(file);
                } catch (IOException e) {
                    request.setAttribute("fileUploadError","上传失败");
//                    e.printStackTrace();
                }

                app_version.setDownloadLink(contextPath+File.separator+fileName);
                app_version.setApkLocPath(path+File.separator+fileName);
                app_version.setApkFileName(fileName);

            }
        }
        Dev_user loginUser= (Dev_user) request.getSession().getAttribute(Constants.USER_SESSION);
        app_version.setModifyBy(loginUser.getId());
        app_version.setModifyDate(new Date());
        if (app_versionService.versionmodify(app_version)>0){
            return "redirect:/dev/app/list";
        }else{
            return "redirect:/dev/appversionmodify";
        }
    }

    @RequestMapping("/delappinfo")
    @ResponseBody
    public Object getDelappinfo(@RequestParam("id")Integer id){
        if (dev_userService.findById(id)==null){
            return JSON.toJSONString("notexist");
        }else {
            if (app_versionService.findByAppid(id)!=null){
                app_versionService.delversion(id);
            }
            dev_userService.delappinfo(id);
            return JSON.toJSONString("true");
        }
    }


    /**
     * APP上架下架功能
     * @param appId
     * @param appstatus
     * @param request
     * @return
     */
    @RequestMapping(value = "/appstatusmodify")
    @ResponseBody
    public Object getAppstatusmodify(@RequestParam("aid")Integer appId,@RequestParam("astatus")String appstatus,
                                     HttpServletRequest request){
        Map<String,String> map=new HashMap<>();
        if (appstatus.equals("open")){
            if (dev_userService.statusmodify(4,appId)>0){
                map.put("errorCode","0");
                map.put("resultMsg","success");
            }else{
                map.put("resultMsg","failed");
            }
        }else if (appstatus.equals("close")){
            if (dev_userService.statusmodify(5,appId)>0){
                map.put("errorCode","0");
                map.put("resultMsg","success");
            }else{
                map.put("resultMsg","failed");
            }
        }else{
            map.put("errorCode","exception000001");
        }
        return JSON.toJSONString(map);
    }






}
